package prv.pursuivant.core.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import prv.pursuivant.core.AchievType;
import prv.pursuivant.core.Achievement;
import prv.pursuivant.core.AllAchievements;
import prv.pursuivant.core.Toon;
import prv.pursuivant.core.ToonAchievements;

import com.google.inject.Inject;

public class AllAchievementsImpl implements AllAchievements {

	private final Map<String, ToonAchievements> achievements;

	@Inject
	public AllAchievementsImpl(Map<String, ToonAchievements> achievements) {
		this.achievements = achievements;
	}

	@Override
	public Achievement get(Toon toon, AchievType achievType) {
		return achievements.get(toon.getName()).get(achievType);
	}

	@Override
	public Achievement get(String toonName, String achievTypeId) {
		return achievements.get(toonName).get(achievTypeId);
	}

	@Override
	public ToonAchievements get(Toon toon) {
		return achievements.get(toon.getName());
	}

	@Override
	public ToonAchievements get(String toonName) {
		return achievements.get(toonName);
	}

	@Override
	public boolean contains(Toon toon, AchievType achievType) {
		return achievements.containsKey(toon.getName())
				&& achievements.get(toon.getName()).contains(achievType);
	}

	@Override
	public boolean contains(String toonName, String achievTypeId) {
		return achievements.containsKey(toonName)
				&& achievements.get(toonName).contains(achievTypeId);
	}

	@Override
	public boolean equals(Object obj) {
		return obj instanceof AllAchievementsImpl
				&& this.achievements
						.equals(((AllAchievementsImpl) obj).achievements);
	}

	@Override
	public int hashCode() {
		return achievements.hashCode();
	}
		
	/**
	 * Creates object from collection of Achievement. 
	 * 
	 * This is factory method for testing purposes only.
	 * @param collection
	 */
	public static AllAchievements fromCollection(Collection<Achievement> collection) {
		Map<String,Map<String,Achievement>> tempMap = new HashMap<String, Map<String,Achievement>>();
		for (Achievement achievement:collection) {
			String toon = achievement.getToon().getName();
			String achievType = achievement.getId();
			if (!tempMap.containsKey(toon)) 
				tempMap.put(toon, new HashMap<String, Achievement>());
			Map<String, Achievement> toonMap = tempMap.get(toon);
			toonMap.put(achievType, achievement);
		}
		Map<String, ToonAchievements> map = new HashMap<String, ToonAchievements>();
		for (String toon : tempMap.keySet())
			map.put(toon, new ToonAchievementsImpl(tempMap.get(toon)));
		return new AllAchievementsImpl(map);
	}

}
